//
//  XDSelectUnitView.m
//  XDEducation
//
//  Created by apple on 2017/4/14.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "XDSelectUnitView.h"
#import "XDCouresUnitModel.h"
@interface XDSelectUnitView ()

@end

@implementation XDSelectUnitView
{
    NSArray *_dataArr;
    UIButton *_selectedButton;
}
-(instancetype)initWithFrame:(CGRect)frame dataArr:(NSArray *)arr{

    if (self = [super initWithFrame:frame]) {
       
        _dataArr = arr;
        
        CGFloat itemW = 150 * ScaleWidth;
        CGFloat itemH = 40 * ScaleHeight;
        
        
        CGFloat padding = (ScreenW - 2 * itemW)/3;
        CGFloat paddingY = 20 * ScaleHeight;
        
        CGFloat itemX = padding;
        CGFloat itemY = paddingY;
        
        int tempI = 0;
        int tempJ = 0;
        for (int i = 0; i < arr.count; i ++) {

            
            XDCouresUnitModel *unitModel = arr[i];
            NSString *title = unitModel.unit_name;
            
            BOOL isMultipleOfFour = !(i % 2);
            
            if (isMultipleOfFour && i != 0) {
                tempJ ++;
                tempI = 0;
                itemY = paddingY + (itemH + paddingY) * tempJ;
            }
            
            
            UIButton *button = [[UIButton alloc]init];
            button.frame =  CGRectMake(itemX + tempI * (padding + itemW), itemY , itemW, itemH);
            
            
            [button setTitle:title forState:UIControlStateNormal];
            
            [button setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            
            [button setBackgroundImage:[UIImage imageNamed:@"list_btn_blue_default"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"list_btn_blue_selected"] forState:UIControlStateSelected];
            
            button.titleLabel.font = [UIFont systemFontOfSize:16];
            button.titleLabel.textAlignment = NSTextAlignmentCenter;
            [self addSubview:button];
            
            tempI ++;
            
            button.tag = i;
            
            
            
            [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
            
        
        }
    }
    return self;
    
}

-(void)buttonClicked:(UIButton *)button{
    
    button.selected = !button.selected;
    
    if (_selectedButton.selected) {
        
        _selectedButton.selected = !_selectedButton.selected;
        
    }
    _selectedButton = button;
    
    XDCouresUnitModel *unitModel = _dataArr[button.tag];
    NSString *title = unitModel.unit_name;
    NSLog(@"选择-%@",title);
    if (self.unitClickedBlock) {
        self.unitClickedBlock(unitModel);
    }
}


@end
